<?php

class Admin_CommonController extends Zend_Controller_Action {

    private $debugLog;
    private $errorLog;

    const CAPACITY_TYPE_MEMORY = 0;
    const CAPACITY_TYPE_CPU = 1;
    const CAPACITY_TYPE_STORAGE = 2;
    const CAPACITY_TYPE_STORAGE_ALLOCATED = 3;
    const CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = 4;
    const CAPACITY_TYPE_PRIVATE_IP = 5;
    const CAPACITY_TYPE_SECONDARY_STORAGE = 6;
    const CAPACITY_TYPE_VLAN = 7;
    const CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 8;
    const CAPACITY_TYPE_LOCAL_STORAGE = 9;

    public function init() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();

        $this->debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
        $this->errorLog = Zend_Registry::get(VirtualLabs_Common::ERROR_LOG);
    }

    public function preDispatch() {
        // Autenticacion del usuario
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_helper->layout->disableLayout();
            $this->_forward("index", "index", "");
        } else {
            $identity = $auth->getIdentity();
            if ($identity['tipo_usuario'] != VirtualLabs_Admin_Usuario::ROL_ADMIN) {
                $this->_helper->layout->disableLayout();
                $this->_redirect('/');
            }
        }
        //fin de la autenicacion del usuario
    }

    public function indexAction() {
        
    }

    public function reservedAction() {
        
    }

    public function cantidadvmAction() {
        $vmDao = new VirtualLabs_Admin_Machine();
        try {
            $vm = $vmDao->getVirtualMachine(array('cuenta' => 'count(*)'));
            if ($vm) {
                echo Zend_Json_Encoder::encode(array('response' => $vm['cuenta']));
            }
        } catch (Exception $e) {
            $this->errorLog->err($e->getTraceAsString());
        }
    }

    public function cantidadlabAction() {
        $labDao = new VirtualLabs_Admin_Laboratorio();
        try {
            $laboratorio = $labDao->getLaboratorio(array('cuenta' => 'count(*)'));
            if ($laboratorio) {
                echo Zend_Json_Encoder::encode(array('response' => $laboratorio['cuenta']));
            }
        } catch (Exception $e) {
            $this->errorLog->err($e->getTraceAsString());
        }
    }

    public function systemcapacityAction() {
        $util = new VirtualLabs_Rest_Util();
        $response = array();
        try {
            $capacity = $util->listCapacity();
            $capacityToString = print_r($capacity, true);
            if (isset($capacity['listcapacityresponse']['count'])) {
                if ($capacity['listcapacityresponse']['count'] > 0) {
                    foreach ($capacity['listcapacityresponse']['capacity'] as $c) {
                        switch ($c['type']) {

                            case self::CAPACITY_TYPE_CPU:

                                $response['cpu'] = array('usado' => $c['capacityused'], 'total' => $c['capacitytotal'], 'libre' => ($c['capacitytotal'] - $c['capacityused']), 'porcentaje_usado' => $c['percentused']);
                                break;
                            case self::CAPACITY_TYPE_MEMORY:
                                $usado = (int) number_format(($c['capacityused'] / 1024 / 1024), 0, ',', '');
                                $total = (int) number_format(($c['capacitytotal'] / 1024 / 1024), 0, ',', '');
                                $libre = (int) number_format((($c['capacitytotal'] / 1024 / 1024) - ($c['capacityused'] / 1024 / 1024)), 0, ',', '');
                                $response['memory'] = array('usado' => $usado, 'total' => $total, 'libre' => $libre, 'porcentaje_usado' => $c['percentused']);
                                break;
                            case self::CAPACITY_TYPE_STORAGE:
                                $usado = (int) number_format(($c['capacityused'] / 1024 / 1024), 0, ',', '');
                                $total = (int) number_format(($c['capacitytotal'] / 1024 / 1024), 0, ',', '');
                                $libre = (int) number_format((($c['capacitytotal'] / 1024 / 1024) - ($c['capacityused'] / 1024 / 1024)), 0, ',', '');
                                $response['storage'] = array('usado' => $usado, 'total' => $total, 'libre' => $libre, 'porcentaje_usado' => $c['percentused']);
                                break;
                            default:
                                break;
                        }
                    }
                    echo Zend_Json_Encoder::encode($response);
                }
            }
            $this->debugLog->debug("Capacity: " . $capacityToString);
        } catch (Exception $e) {
            $this->errorLog->err($e->getTraceAsString());
        }
    }

    /**
     * Obtiene la lista de ISOs disponibles en cloudstack
     */
    private function getListIsos() {
        $t = new VirtualLabs_Rest_VirtualLabs_ISO();
        $list = $t->listIsos();

        foreach ($list['listisosresponse']['iso'] as $iso) {
            $retorno .= '<option value="' . $iso['id'] . '">' . $iso['displaytext'] . '</option>';
        }
        echo $retorno;
    }

    /**
     * Obtiene la lista de templates disponibles en cloudstack
     */
    public function listtemplatesAction() {
        $tipo = $this->getRequest()->getParam("tipo");
        if ($tipo == 0) {
            echo $this->getListTemplates();
        } else if ($tipo == 1) {
            echo $this->getListIsos();
        }
    }

    private function getListTemplates() {
        $t = new VirtualLabs_Rest_VirtualLabs_Template();
        $list = $t->listTemplates();

        foreach ($list['listtemplatesresponse']['template'] as $template) {
            $retorno .= '<option value="' . $template['id'] . '">' . $template['displaytext'] . '</option>';
        }
        return $retorno;
    }

    public function listdiskofferingsAction() {
        $t = new VirtualLabs_Rest_VirtualLabs_Offerings();
        $list = $t->listDiskOfferings();
        ;
        foreach ($list['listdiskofferingsresponse']['diskoffering'] as $disk) {
            $retorno .= '<option value="' . $disk['id'] . '">' . $disk['displaytext'] . ' | ' . $disk['disksize'] . ' GB</option>';
        }
        echo $retorno;
    }

    public function listserviceofferingsAction() {

        $t = new VirtualLabs_Rest_VirtualLabs_Offerings();
        $list = $t->listServiceOfferings();
        foreach ($list['listserviceofferingsresponse']['serviceoffering'] as $disk) {
            $retorno .= '<option value="' . $disk['id'] . '">' . $disk['displaytext'] . ' | ' . $disk['cpunumber'] . ' of ' . $disk['cpuspeed'] . ' MHz | ' . $disk['memory'] . ' MB</option>';
        }
        echo $retorno;
    }

    public function getdateAction() {
        $db = Zend_Db_Table::getDefaultAdapter();
        $sql = "SELECT CURDATE()";
        return $db->fetchRow($sql);
    }

    public function cantidadmaquinasactivasAction() {
        $vm = new VirtualLabs_Admin_Machine();
        echo Zend_Json_Encoder::encode(array("cantidad_activa" => $vm->getActiveMachines(), "cantidad_total" => $vm->getAllMachines()));
    }

}

